﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Management;

namespace XMM.Dialoges
{
    /// <summary>
    /// Interaktionslogik für SetupSettings.xaml
    /// </summary>
    public partial class SetupSettings : Window
    {
        Settings oSettings = new Settings();

        XMM.Library ParentLibrary;

        private bool IsDBChanged { get; set; }

        public SetupSettings(XMM.Library dlgParentLibrary)
        {
            InitializeComponent();

            ParentLibrary = dlgParentLibrary;
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            loadSettings();
        }

        private void loadSettings()
        {
            oSettings = new Settings();

            if (oSettings != null)
            {
                /***********************************
                 * Get Medialibrary-Settings.
                 * */
                txtLibraryPath.Text = oSettings.LibraryDataStorage;

                if (System.IO.Directory.Exists(oSettings.LibraryDataStorage))
                {                    
                    lblUsedLibrarySpace.Content = getUsedDirectorySpace(oSettings.LibraryDataStorage) + " MB";

                    lblUsedCacheSpace.Content = getUsedDirectorySpace(oSettings.LibraryDataStorage + "tvdb") + " MB";

                    lblFreeLibrarySpace.Content = getFreeDiskSpace(oSettings.LibraryDataStorage) + " MB";
                }

                /***********************************
                 * Get Video-Player-Settings.
                 * */
                txtVideoPlayerPath.Text = oSettings.VLCExecutablePath;

                switch (oSettings.VideoPlayerExtensions)
                {
                    case 0:
                        rdbVideoPlayerExtensionNone.IsChecked = true;
                        break;
                    case 1:
                        rdbVideoPlayerExtensionVLC.IsChecked = true;
                        break;
                    case 2:
                        rdbVideoPlayerExtensionWMP.IsChecked = true;
                        break;
                }

                /***********************************
                 * Get Database-Settings.
                 * */
                txtDatabaseFilePath.Text = oSettings.DatabaseStoragePath;

                // Get Database-Storage-Path-Replacement for "\XMM.mdf".
                string sDatabaseStoragePath = oSettings.DatabaseStoragePath;
                if (oSettings.DatabaseStoragePath == "\\XMM.mdf")
                    sDatabaseStoragePath = Tools.getInstallationPath() + "XMM.mdf";
                
                // Get Database-File-Details.
                if (System.IO.File.Exists(sDatabaseStoragePath))
                {
                    // Update Filesize.
                    System.IO.FileInfo fiDatabaseFile = new System.IO.FileInfo(sDatabaseStoragePath);
                    lblDBFilesize.Content = Tools.ConvertBytesToMegabytes(fiDatabaseFile.Length);

                    // Do Connection-Test.
                    try
                    {
                        XMMDBDataContext dbConnection = new XMMDBDataContext();
                        dbConnection.Connection.Open();
                        txtConnectionTest.Text = "Verbindung OK: MSSQL " + dbConnection.Connection.ServerVersion + Environment.NewLine + dbConnection.Connection.DataSource;
                        dbConnection.Connection.Close();
                    }
                    catch (Exception ex)
                    {
                        txtConnectionTest.Text += Environment.NewLine + "ERROR: " + ex.Message;
                    }
                }
                else
                {
                    lblDBFilesize.Content = "Datei nicht gefunden!";
                    txtConnectionTest.Text = "Datei nicht gefunden!";
                }

                // Get Online-Settings.
                if (oSettings.CheckForUpdates)
                {
                    chkAutomaticUpdates.IsChecked = true;
                    cmbUpdateInterval.IsEnabled = true;
                    switch (oSettings.CheckForUpdatesInterval)
                    {
                        case 7:
                            cmbUpdateInterval.SelectedIndex = 0;
                            break;
                        case 14:
                            cmbUpdateInterval.SelectedIndex = 1;
                            break;
                        case 30:
                            cmbUpdateInterval.SelectedIndex = 2;
                            break;
                    }
                }
                else
                {
                    chkAutomaticUpdates.IsChecked = false;
                    cmbUpdateInterval.IsEnabled = false;
                    cmbUpdateInterval.SelectedIndex = -1;
                }
            }

            IsDBChanged = false;
        }

        public static decimal getUsedDirectorySpace(string sPath)
        {
            decimal dUsedSpace = 0;
            float fTemp = 0;

            if(System.IO.Directory.Exists(sPath))
            {
                string[] saFiles = System.IO.Directory.GetFiles(sPath, "*.*", System.IO.SearchOption.AllDirectories);

                foreach (string sFile in saFiles)
                {
                    System.IO.FileInfo fiFile = new System.IO.FileInfo(sFile);
                    float fSize = (float)fiFile.Length;
                    fSize = fSize / 1024 / 1024;
                    fTemp += fSize;
                }
            }

            dUsedSpace = (decimal)fTemp;
            dUsedSpace = Math.Round(dUsedSpace, 2);

            return dUsedSpace;
        }

        public static decimal getFreeDiskSpace(string sPath)
        {
            decimal dFreeSpace = 0;

            ManagementObject moDisk = new ManagementObject("win32_logicaldisk.deviceid=\""+ sPath.Remove(1, (sPath.Length - 1)) + ":\"");
            moDisk.Get();

            if (moDisk != null)
            {
                Int64 iFreeSpaceBytes = Int64.Parse(moDisk["FreeSpace"].ToString());
                dFreeSpace = iFreeSpaceBytes / 1024 / 1024;
            }

            return dFreeSpace;
        }

        private void btnAbort_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }

        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            // Get Medialibrary-Path.
            if (txtLibraryPath.Text != String.Empty && System.IO.Directory.Exists(txtLibraryPath.Text))
                oSettings.LibraryDataStorage = txtLibraryPath.Text;
            else
            {
                MessageBox.Show("Der Pfad für die Medienbibliothek \"" + txtLibraryPath.Text + "\" wurde nicht gefunden!", "Fehler", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            // Get DatabaseFilePath.
            if (txtDatabaseFilePath.Text != String.Empty)
                oSettings.DatabaseStoragePath = txtDatabaseFilePath.Text;
            else
            {
                MessageBox.Show("Keine Datenbank angegeben!", "Fehler", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
            
            // Get Video-Player-Path.
            if (txtVideoPlayerPath.Text != String.Empty && System.IO.File.Exists(txtVideoPlayerPath.Text))
                oSettings.VLCExecutablePath = txtVideoPlayerPath.Text;

            // Get Video-Player-Extensions.
            oSettings.VideoPlayerExtensions = 0;

            if ((bool)rdbVideoPlayerExtensionVLC.IsChecked)
                oSettings.VideoPlayerExtensions = 1;
            else if ((bool)rdbVideoPlayerExtensionWMP.IsChecked)
                oSettings.VideoPlayerExtensions = 2;

            // Get Online-Settings.
            oSettings.CheckForUpdates = (bool)chkAutomaticUpdates.IsChecked;
            if (oSettings.CheckForUpdates)
                oSettings.CheckForUpdatesInterval = int.Parse(((ComboBoxItem)cmbUpdateInterval.SelectedItem).Content.ToString());

            if (oSettings.Save())
            {
                /*
                ParentLibrary.RefreshXMM();
                ParentLibrary.RefreshAudiences();
                Close();
                 * */

                if (IsDBChanged)
                {
                    if (MessageBox.Show("Um die Änderungen zu übernehmen muss XMM neu gestartet werden! Jetzt neu starten?", "Neustart ausstehend", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
                    {
                        ParentLibrary.updateConnectionString();
                        ParentLibrary.Shutdown();
                    }
                }

                ParentLibrary.RefreshXMM();
                this.Close();
            }
        }

        private void btnBrowseLibraryPath_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.FolderBrowserDialog dlgBrowser = new System.Windows.Forms.FolderBrowserDialog();
            dlgBrowser.ShowNewFolderButton = true;

            if (txtLibraryPath.Text != String.Empty)
                dlgBrowser.RootFolder = Environment.SpecialFolder.MyComputer;

            if (dlgBrowser.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                txtLibraryPath.Text = dlgBrowser.SelectedPath + "\\";
            }
        }

        private void btnBrowseVideoPlayerPath_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.OpenFileDialog dlgBrowser = new System.Windows.Forms.OpenFileDialog();
            dlgBrowser.CheckFileExists = true;
            dlgBrowser.FileName = "vlc.exe";
            dlgBrowser.Filter = "Video-Player Hauptanwendung|*.exe";

            dlgBrowser.Multiselect = false;
            dlgBrowser.RestoreDirectory = true;
            dlgBrowser.Title = "Video-Player Auswahl";

            if (dlgBrowser.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                txtVideoPlayerPath.Text = dlgBrowser.FileName;
            }
        }

        private void btnBrowseDBFile_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.OpenFileDialog dlgBrowser = new System.Windows.Forms.OpenFileDialog();
            dlgBrowser.CheckFileExists = true;
            dlgBrowser.FileName = "XMM.mdf";
            dlgBrowser.Filter = "MS SQL Datenbank-Datei|*.mdf";
            dlgBrowser.Multiselect = false;
            dlgBrowser.RestoreDirectory = true;
            dlgBrowser.Title = "Datenbank-Datei für XMM auswählen";

            if (dlgBrowser.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                txtDatabaseFilePath.Text = dlgBrowser.FileName;
                txtConnectionTest.Text = "Datenbank-Datei gefunden!";
            }
        }

        private void chkAutomaticUpdates_Checked(object sender, RoutedEventArgs e)
        {
            cmbUpdateInterval.IsEnabled = true;

            switch (oSettings.CheckForUpdatesInterval)
            {
                case 7:
                    cmbUpdateInterval.SelectedIndex = 0;
                    break;
                case 14:
                    cmbUpdateInterval.SelectedIndex = 1;
                    break;
                case 30:
                    cmbUpdateInterval.SelectedIndex = 2;
                    break;
            }
        }

        private void chkAutomaticUpdates_Unchecked(object sender, RoutedEventArgs e)
        {
            cmbUpdateInterval.IsEnabled = false;
            cmbUpdateInterval.SelectedIndex = -1;
        }

        private void txtDatabaseFilePath_TextChanged(object sender, TextChangedEventArgs e)
        {
            IsDBChanged = true;
        }
    }
}
